package cn.miaoyao.miaoyaoms.controller;


import cn.miaoyao.miaoyaoms.entity.Article;
import cn.miaoyao.miaoyaoms.entity.Limits;
import cn.miaoyao.miaoyaoms.entity.User;
import cn.miaoyao.miaoyaoms.service.ArticleService;
import cn.miaoyao.miaoyaoms.service.LimitsService;
import cn.miaoyao.miaoyaoms.service.UserService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonAlias;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sun
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private LimitsService limitsService;
    @Autowired
    private ArticleService articleService;

    /**
     * 实现注册
     * @param user
     * @return
     */
    @PostMapping("register")
    public String register(User user) {
        LambdaQueryWrapper<User> lw = new LambdaQueryWrapper<>();
        //避免手机号重复，邮箱重复
        lw.eq(User::getPhone,user.getPhone()).or().eq(User::getEmail,user.getEmail()).eq(User::getUsername,user.getUsername());
        List<User> users =  userService.list(lw);
        if (users.size()==0) {
            userService.save(user);
            return "false";
        }
        return JSON.toJSONString(users.get(0));
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @param request
     * @return
     */
    @PostMapping("/login")
    public boolean login(String username, String password, HttpServletRequest request){
        LambdaQueryWrapper<User> lsw = new LambdaQueryWrapper<>();
        lsw.eq(User::getUsername,username).eq(User::getPassword,password);
        //通过条件查询看用户是否存在
        User user=userService.getOne(lsw);
        if(user!=null){//表示登录成功。
                //获取到对应的用户权限
                Limits userLimits = limitsService.getById(user.getUid());
                if(!ObjectUtils.isEmpty(userLimits)) {
                    request.getSession().setAttribute("user", user);//将用户信息存在session中。
                    request.getSession().setAttribute("limits", userLimits);
                    return true;
            }
        }
        return false;
    }

    /**
     * 前端获取用户信息
     * @param page 第几页
     * @param limits 一页多少条
     * @param username 用户名
     * @param phone 用户号码
     * @param email 用户邮箱
     * @param request
     * @return
     */
    @PostMapping("userInfo")
    public String searchInfo(@RequestParam(name = "page",defaultValue ="1") Long page,
                             @RequestParam(name = "limit",defaultValue = "10") Long limits,
                             String username,String phone,String email,HttpServletRequest request){
        Page<User> userPage = new Page<>(page,limits);
        HashMap<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<User> lsw = new LambdaQueryWrapper<>();
        Limits userPermissions = (Limits) request.getSession().getAttribute("limits");//获取权限然后根据权限进行操作。
        Integer addUserPermission=0,deleteUserPermission=0;
        if(!ObjectUtils.isEmpty(username))
            lsw.eq(User::getUsername,username);
        if(!ObjectUtils.isEmpty(phone))
            lsw.eq(User::getPhone,phone);
        if(!ObjectUtils.isEmpty(email))
            lsw.eq(User::getEmail,email);
        //lsw.eq(User::getUsername,username).eq(User::getPhone,phone).eq(User::getEmail,email);
        userService.page(userPage,lsw);
        if(userPermissions.getAdduser()==1)
            addUserPermission=1;
        if(userPermissions.getDeleteuser()==1)
            deleteUserPermission=1;
        map.put("code",0);
        map.put("msg","");
        //获取总数量
        map.put("count",userPage.getTotal());
        map.put("addPermission",addUserPermission);
        map.put("deletePermission",deleteUserPermission);
        //发送总数据
        map.put("data", userPage.getRecords());
        return JSON.toJSONString(map);
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @GetMapping("logout")
    public String logout(HttpServletRequest request){
        //清除会话中的数据
        request.getSession().removeAttribute("user");
        request.getSession().removeAttribute("limits");
        return "/login.html";
    }

    /**
     * 添加用户（管理员）
     * @param user
     * @return
     */
    @PostMapping(value = "userAdd",produces = "application/json;charset=utf-8")
    public String addUser(@RequestBody User user){
        LambdaQueryWrapper<User> lsw = new LambdaQueryWrapper<>();
        HashMap<String, Object> map = new HashMap<>();
        lsw.eq(User::getPhone,user.getPhone()).or().eq(User::getEmail,user.getEmail());
        List<User> isUser = userService.list(lsw);
        if(ObjectUtils.isEmpty(isUser)&&user!=null){
            LambdaQueryWrapper<User> userlsw = new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername());
            User one = userService.getOne(userlsw);
            if(ObjectUtils.isEmpty(one)){
                userService.save(user);
               map.put("msg","添加成功");
           }else{
               map.put("msg","用户名已被注册");
           }
            return JSON.toJSONString(map);
        }
        map.put("msg","手机号或邮箱已被注册过");
        return JSON.toJSONString(map);
    }

    /**
     * 根据用户id进行删除
     * @param uid
     * @return
     */
    @PostMapping("deleteUser/{uid}")
    public Boolean deleteUser(@PathVariable Integer uid){
        User user = userService.getById(uid);
        if(!ObjectUtils.isEmpty(user)){//当人存在的时候，就进行删除。
            boolean b = userService.removeById(uid);
            return b;
        }
        return  false;
    }

    /**
     * 返回用户名
     * @param request
     * @return
     */
    @GetMapping("user/getUsername")
    public String getUsername(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        return user.getUsername();
    }

    /**
     * 打开首页的时候，异步数据到首页界面进行展示。
     * @param request
     * @return
     */
    @GetMapping("/getuser")
    public String getUser(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");//获取session中的user信息展示到页面当中。
        LambdaQueryWrapper<Article> asw = new LambdaQueryWrapper<>();
        HashMap<String, Object> map = new HashMap<>();
        asw.eq(Article::getUid,user.getUid());
        List<Article> list = articleService.list(asw);
        map.put("username",user.getUsername());
        map.put("phone",user.getPhone());
        map.put("email",user.getEmail());
        map.put("uid",user.getUid());
        map.put("articles",JSON.toJSONString(list));
        return JSON.toJSONString(map);
    }

}

